﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StructureDiagram;

namespace RegExpParser
{
    public class RegExpParser
    {
        /// <summary>
        /// Parse regular expression string to diagram
        /// </summary>
        /// <param name="regularExpression">Regular expression string</param>
        /// <param name="diagram">Result diagram</param>
        /// <param name="errorText">Error description, empty if parsing was successfull</param>
        /// <returns>Returns true if parsing was successfull or false otherwise</returns>
        public static bool ParseRegExp(string regularExpression, out Diagram diagram, 
            out string errorText)
        {
            diagram = new Diagram();
            errorText = "";

            int strPos = 0;
            DiagramElement previousElement = null;

            while (strPos < regularExpression.Length)
            {
                string elementText = regularExpression[strPos].ToString();

                TextDiagramElement textElement = new TextDiagramElement(elementText);
                {
                    diagram.AddElement(textElement, previousElement, null);
                }

                strPos++;
            }            

            return true;
        }
        /// <summary>
        /// Create regular expression string by diagram
        /// </summary>
        /// <param name="diagram">Input diagram</param>
        /// <param name="regularExpression">Result regular expression string</param>
        /// <param name="errorText">Error description, empty if creation was successfull</param>
        /// <returns>Returns true if creation was successfull or false otherwise</returns>
        public static bool CreateRegExp(Diagram diagram, out string regularExpression,
            out string errorText)
        {
            regularExpression = "";
            errorText = "";

            DiagramElement firstElement = diagram.GetFirstElement();
            
            if (firstElement == null)
            {
                errorText = "Cannot find first element of the diagram";
                return false;
            }

            DiagramElement currentElement = firstElement;

            while (currentElement != null)
            {
                if(currentElement is TextDiagramElement)
                {
                    TextDiagramElement textDiagramElement = 
                        (TextDiagramElement) currentElement;
                    regularExpression += textDiagramElement.Text;
                }

                List<DiagramElement> nextElements = currentElement.GetNextElements();

                if (nextElements.Count > 0)
                    currentElement = nextElements[0];
                else
                    currentElement = null;
            }

            return true;
        }
    }
}
